package com.echat.companydata.service;

import com.alibaba.fastjson.JSON;
import com.echat.commonlib.exception.exc.ValidateFailedException;
import com.echat.companydata.tool.*;
import com.echat.companydata.util.CompanyDataRedisUtil;
import com.echat.companydata.vo.CompanyRecentData;
import com.echat.companydata.vo.DepartmentInfo;
import com.echat.companydata.vo.StaffInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;

/**
 * Created by chenmohan on 2018/09/21
 *
 * @description
 */
@Service
public class FetchDataService {

   // @Autowired
   // StringRedisTemplate redisTemplate;

    /**
     * 获取指定公司访客在线数量
     *
     * @param companyId
     * @return
     */
    public long getCompanyVisitorOnLineNumber(Long companyId) {
        assertCompanyIdNotNull(companyId);
        Long number = CompanyDataRedisUtil.getCompanyVisitorOnLineNumber(companyId);
       // Long number = redisTemplate.opsForHash().size(RedisKey.companyVisitorMapKey(companyId));
        if (number == null) {
            return -1;
        }
        return number;
    }

    /**
     * 获取指定公总共聊天数量
     *
     * @param companyId
     * @return
     */
    public long getCompanyTotalChatNumber(Long companyId) {
        assertCompanyIdNotNull(companyId);
        Long number = CompanyDataRedisUtil.getCompanyTotalChatNumber(companyId);
        if (number == null) {
            return -1;
        }
        return number;
    }

    /**
     * 获取公司当前已登录的客服状态
     *
     * @param companyId
     * @return
     */
    public Map<Integer, Integer> getStaffStatusMap(Long companyId) {
        assertCompanyIdNotNull(companyId);
        Map<String, String> map =CompanyDataRedisUtil.getStaffStatusMap(companyId);
        // Map<String, String> map = (Map<String, String>) (Map) redisTemplate.opsForHash().entries(RedisKey.staffStatusKey(companyId));
        if (map != null) {
            map.remove(RedisKey.companyStatus);
        }
        /*TODO:  lambda not test
        map.entrySet().parallelStream().collect(Collectors.groupingBy(e->Long.valueOf(e.getValue())) )
                        .entrySet().parallelStream().collect(Collectors.toMap(e->e.getKey(),e->e.getValue().size()));
        */
        //获得指定公司的当前客服状态数量
        Map<Integer, Integer> staffStatusCountMap = new HashMap<>();
        int[] status = new int[4];
        for (Map.Entry<String, String> e : map.entrySet()) {
            switch (e.getValue()) {
                case "1":       //在线
                    status[0]++;
                    break;
                case "2":       //忙碌
                    status[1]++;
                    break;
                case "3":       //离开
                    status[2]++;
                    break;
                case "4":       //隐身
                    status[3]++;
                    break;
            }
        }
        for (int i = 0; i < status.length; ++i) {
            staffStatusCountMap.put(i + 1, status[i]);
        }
        return staffStatusCountMap;
    }

    public CompanyRecentData getComanyDataByDate(Long companyId , Calendar c){
        assertCompanyIdNotNull(companyId);
        Assert.notNull(c,"arg[Calendar]不能为空");
        String dateKey = DateFormatUtil.getYyyyMMdd(c.getTime());
        CompanyRecentData data = new CompanyRecentData();
        data.setDate(dateKey);
        String dailyDataKey = RedisKey.companyDailyDataKey(companyId, dateKey);
        Map<String, String> comanyRawDataMap = CompanyDataRedisUtil.getComanyRawDataMap(dailyDataKey);
      //  Map<String, String> comanyRawDataMap = (Map)redisTemplate.opsForHash().entries(dailyDataKey);
        if (comanyRawDataMap != null && comanyRawDataMap.size() > 0) {
            //新访客数量
            if (StringUtil.isNotEmpty(comanyRawDataMap.get(RedisKey.DailyCountKey.newvCount))) {
                data.setNewVisitorNumber(Integer.valueOf(comanyRawDataMap.get(RedisKey.DailyCountKey.newvCount)));
            }
            //登录客服数量
            if (StringUtil.isNotEmpty(comanyRawDataMap.get(RedisKey.DailyCountKey.staffLogins))) {
                data.setLoginStaffNumber(Integer.valueOf(comanyRawDataMap.get(RedisKey.DailyCountKey.staffLogins)));
            }
            //访客数量
            if (StringUtil.isNotEmpty(comanyRawDataMap.get(RedisKey.DailyCountKey.vCount))) {
                data.setVisitorNumber(Integer.valueOf(comanyRawDataMap.get(RedisKey.DailyCountKey.vCount)));
            }
            //对话数量
            if (StringUtil.isNotEmpty(comanyRawDataMap.get(RedisKey.DailyCountKey.cCount))) {
                data.setChatNumber(Integer.valueOf(comanyRawDataMap.get(RedisKey.DailyCountKey.cCount)));
            }
        }
        return data;

    }

    /**
     * 获取客服信息列表
     *
     * @param companyId
     * @return
     */
    public  List<StaffInfo> getStaffInfoList(Long companyId) {
        assertCompanyIdNotNull(companyId);
        List<StaffInfo> list = new ArrayList<>();
        Set staffIdSet = CompanyDataRedisUtil.getStaffIdSet(companyId);
        // Set<String> staffIdSet = (Set)redisTemplate.opsForHash().keys(ChatRedisKeys.getChatProfileStaffInfoKey(companyId));
        if (staffIdSet == null || staffIdSet.size() == 0) {
            return list;

        }

        Iterator<String> iterator = staffIdSet.iterator();
        while (iterator.hasNext()) {
            String staffId = iterator.next();
            String msg = CompanyDataRedisUtil.getStaffInfo(companyId, staffId);
            // String msg = (String)redisTemplate.opsForHash().get(ChatRedisKeys.getChatProfileStaffInfoKey(companyId), String.valueOf(staffId));
            if (StringUtil.isNotEmpty(msg)) {
                list.add((StaffInfo) JSON.parseObject(msg, StaffInfo.class));
            }
        }
        return list;
    }

    /**
     * 查询staff查询所属部门名
     *
     * @param companyId
     * @param departmentIds 所属部门id
     * @return
     */
    public List<String> getDeparmentList(Long companyId, String departmentIds) {
        if (StringUtil.isEmpty(departmentIds)) {
            return Collections.EMPTY_LIST;
        }
        String[] ids = departmentIds.split(Constants.COMMA);
        List<String> departmentNameList = new ArrayList<>(ids.length);
        for (String id : ids) {
            DepartmentInfo info = getDepartmentInfo(companyId, Long.valueOf(id));
            if (info != null) {
                departmentNameList.add(info.getDepartmentName());
            }
        }
        return departmentNameList;
    }

    private DepartmentInfo getDepartmentInfo(Long companyId, Long departmentId) {
        String msg = CompanyDataRedisUtil.getDepartmentInfo(companyId, departmentId);
        //String msg = (String)redisTemplate.opsForHash().get(ChatRedisKeys.getDepartmentMap(companyId), String.valueOf(departmentId));
        if (StringUtil.isEmpty(msg)) {
            /*
            refreshDepartmentMap(companyId);
            msg = redis.hget(ChatRedisKeys.getDepartmentMap(companyId), String.valueOf(departmentId));
            if (StringUtil.isEmpty(msg)) {
                return null;
            }*/
            return null;
        }
        return JSON.parseObject(msg, DepartmentInfo.class);
    }

    private void assertCompanyIdNotNull(Long companyId) {
        if(companyId == null){
            throw new ValidateFailedException("缺少必要的接口参数");
        }
    }


}
